package com.sss.demo.dao.impl;

import com.sss.demo.dao.IUser;
import com.sss.demo.entity.User;
import com.sss.demo.util.DBUtil;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
*   根据对应的接口创建对应的实现类的名称
*   后缀添加impl...         implements的简写
*
*   IUserImpl的作用：
*                   就是写连接数据库代码，并创建sql语句实现CRUD的实现
* */
public class IUserImpl implements IUser {
    //声明一个Connection对象
    Connection conn;

    @Override
    public boolean login(User user) throws SQLException {
        boolean flag = false;
        conn = DBUtil.getConnection();
        String sql = "select * from tb_user where name = ? and password = ?";
        PreparedStatement prestat = conn.prepareStatement(sql);
        prestat.setString(1,user.getName());
        prestat.setString(2,user.getPassword());
        ResultSet rs = prestat.executeQuery();
        if(rs.next()){flag= true;}
        return flag;
    }

    @Override
    public boolean register(User user) throws SQLException {
        conn=DBUtil.getConnection();
        String sql="insert tb_user(name,password) values(?,?)";
        PreparedStatement prestat = conn.prepareStatement(sql);
        prestat.setString(1,user.getName());
        prestat.setString(2,user.getPassword());
        int i=prestat.executeUpdate();
        if(i==1){
            return true;
        }
        return false;
    }

    @Override
    public boolean selectOne(User user) throws SQLException {
        conn=DBUtil.getConnection();
        String sql="select * from tb_user where name=?";
        PreparedStatement prestat = conn.prepareStatement(sql);
        prestat.setString(1,user.getName());
        ResultSet rs = prestat.executeQuery();
        if(rs.next()){
            return true;
        }
        return false;
    }
}